<template>
    <view class="main">
        <view class="query" id="query" ref="queryRef">
            <view class="one">
                <view class="ipt">
                    <input type="text" v-model="queryParams.stationName" placeholder="请输入换电站">
                </view>
                <view class="sel">
                    <uni-data-select v-model="queryParams.state" :localdata="cateTwoList"
                        :clear="false"></uni-data-select>
                </view>
            </view>
            <view class="two">
                <view class="item" @click="openCalendar">
                    <view class="left">{{ queryParams.startTime && queryParams.startTime ? queryParams.startTime + ' ~ '
                        +
                        queryParams.endTime :
                        '年/月/日' }}</view>
                    <view class="right">
                        <image src="/static/icon/rl.png" mode="scaleToFill" />
                    </view>
                </view>
            </view>
            <view class="button">
                <view class="b">
                    <button class="reset btn" @click="reset">重 &nbsp;&nbsp;&nbsp; 置</button>
                    <button class="search btn" @click="search">查&nbsp;&nbsp;&nbsp;询</button>
                </view>
            </view>
        </view>
        <view class="list" :style="{ marginTop: queryHeight + 'px' }">
            <OrderCard v-for="item in dataList" :key="item" :orderItem="item" />
            <LoadMore :state="state" />
        </view>
    </view>
    <wd-calendar ref="calendar" :with-cell="false" type="daterange" v-model="time" @confirm="handleConfirm" />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { formatDateTime, getElementHeight } from '@/utils/tools'
import OrderCard from './components/OrderCard.vue'
import LoadMore from '@/components/loadMore/LoadMore.vue'
import { onLoad, onReachBottom, onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { orderList } from '@/api/apiList'

let state = ref('finished')

// 获取当前日期
const currentDate = new Date();
// 获取当前年月日（格式：YYYY-MM-DD）
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份补零
const day = String(currentDate.getDate()).padStart(2, '0'); // 日期补零
const today = `${year}-${month}-${day}`;

// 获取一年后的日期
const nextYearDate = new Date(currentDate);
nextYearDate.setFullYear(nextYearDate.getFullYear() - 1);
const nextYear = `${nextYearDate.getFullYear()}-${String(nextYearDate.getMonth() + 1).padStart(2, '0')}-${String(nextYearDate.getDate()).padStart(2, '0')}`;

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    startTime: nextYear,
    endTime: today,
    stationName: '',
    state: ''
})
const dataList = ref([])
const getList = async () => {
    for (const key in queryParams.value) {
        if (!queryParams.value[key]) {
            delete queryParams.value[key]
        }
    }
    state.value = 'loading' // finished error
    const { code, msg, rows, total } = await orderList(queryParams.value)
    if (code == 200) {
        if (total == 0) {
            state.value = 'finished'
        } else {
            if (rows.length == 0) {
                state.value = 'finished'
            } else {
                state.value = 'finished'
                dataList.value = [...dataList.value, ...rows]
            }
        }
    } else {
        state.value = 'error'
    }
}

const search = () => {
    init()
    getList()
}

onShow(() => {
    dataList.value = []
    queryParams.value.pageNum = 1
    state.value = 'finished'
    getList()
})

onLoad(() => {
    // sq()
})

const sq = () => {
    if (uni.getStorageSync('isDing') == 2) {
        uni.showModal({
            content: '检测到您没打开获取信息功能权限，是否去设置打开？',
            confirmText: "确认",
            cancelText: '取消',
            success: (res) => {
                if (res.confirm) {
                    uni.openSetting({
                        success: (res) => {
                            console.log(res);
                        }
                    })
                } else {
                    console.log('取消');
                }
            }
        })
    }
}

onReachBottom(() => {
    queryParams.value.pageNum++
    getList()
})

onPullDownRefresh(() => {
    uni.showLoading({
        title: '加载中',
        icon: 'none'
    })
    queryParams.value.pageNum = 1
    dataList.value = []
    getList().finally(() => {
        uni.hideLoading()
        uni.stopPullDownRefresh()
    })
})

const time = ref([])
const calendar = ref(null)
const queryRef = ref(null)

const openCalendar = () => {
    calendar.value.open()
}

const handleConfirm = ({ value }) => {
    queryParams.value.startTime = formatDateTime(value[0])
    queryParams.value.endTime = formatDateTime(value[1])
}

const init = () => {
    queryParams.value.pageNum = 1
    dataList.value = []
}

const reset = () => {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        startTime: nextYear,
        endTime: today,
        stationName: '',
        state: ''
    }
    init()
    getList()
}


const cateTwoList = ref([
    { value: 1, text: "待支付" },
    { value: 3, text: "已完成" },
    { value: 4, text: "已取消" },
])

let queryHeight = ref(0)
onMounted(async () => {
    queryHeight.value = await getElementHeight('#query')
})

</script>

<style lang="scss" scoped>
.main {
    padding: 20rpx;

    .query {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background-color: #fff;
        box-sizing: border-box;
        padding: 20rpx;

        .one {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .ipt {
                width: 48%;
                border-radius: 5rpx;

                input {
                    padding: 5px 0 5px 10px;
                    border: 1rpx solid #e5e5e5;
                    font-size: 26rpx;
                    border-radius: 7rpx;
                }
            }

            .sel {
                width: 48%;
            }
        }

        .two {
            margin-top: 20rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-sizing: border-box;

            .item {
                padding: 10rpx;
                width: 100%;
                border-bottom: 1rpx solid #e5e5e5;
                display: flex;
                justify-content: space-between;
                align-items: center;
                box-sizing: border-box;

                .left {
                    font-size: 26rpx;
                    color: #444;
                }

                .right {
                    image {
                        width: 50rpx;
                        height: 50rpx;
                    }
                }
            }
        }

        .button {
            margin-top: 40rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;

            .b {
                display: flex;
                align-items: center;
            }

            .btn {
                padding: 0 100rpx;
                font-size: 26rpx;
                border-radius: 7rpx;
            }

            .reset {
                margin-right: 20rpx;
                background-color: #fff;
                color: #444;
                border: 1rpx solid #55946d;
            }

            .search {
                background-color: #55946d;
                color: #fff;
            }
        }
    }
}

.calendar {
    padding-top: 40rpx;
}
</style>